﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MuffinBreak.Bll
{
    public class StoreVote
    {
        public int Id { get; private set; }
        public string Store { get; private set; }
        public string Barrista { get; private set; }
        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public string EmailAddress { get; private set; }
        public bool AllowUpdates { get; private set; }
        public string ContactTel { get; private set; }
        public DateTime Updated { get; private set; }

        private class JoinHelper
        {
            public Post Post { get; set; }
            public PostControl BarristaControl { get; set; }
            public Vote Vote{ get; set; }
        }

        private static IQueryable<JoinHelper> Select(MuffinBreakDataContext dataContext)
        {
            var tmp = dataContext.Votes.Join(
                        dataContext.Posts.Where(x => x.PublishFrom.HasValue && x.PublishFrom <= DateTime.Now.ToUniversalTime() && (x.PublishTo ?? DateTime.MaxValue) > DateTime.Now.ToUniversalTime()),
                        x => x.PostGuid,
                        y => y.PostGuid,
                        (x, y) => new { Vote = x, Post = y });
            return tmp.Select(x => new JoinHelper() { Post = x.Post, Vote = x.Vote, BarristaControl = x.Post.PostControls.Where(y => y.TemplateControl.Name == "Barrista Name").FirstOrDefault() });
        }

        private static IQueryable<StoreVote> Convert(IQueryable<JoinHelper> source)
        {
            return source.Select(x => Convert(x));
        }

        private static StoreVote Convert(JoinHelper source)
        {
            if (source != null)
            {
                var tmp = new StoreVote();
                tmp.Id = source.Vote.Id;
                tmp.AllowUpdates = source.Vote.AllowUpdates;
                tmp.FirstName = source.Vote.FirstName;
                tmp.LastName = source.Vote.LastName;
                tmp.EmailAddress = source.Vote.EmailAddress;
                tmp.ContactTel = source.Vote.ContactTel;
                tmp.Updated = source.Vote.Updated;
                tmp.Store = source.Post.DisplayName;
                if (source.BarristaControl != null && source.BarristaControl.Value != null)
                    tmp.Barrista = source.BarristaControl.Value.Value;
                return tmp;
            }
            else
            {
                return null;
            }
        }


        public static List<StoreVote> GetAll(MuffinBreakDataContext dataContext)
        {
            var tmp = Select(dataContext);
            return Convert(tmp).ToList();
        }
    }
}
